<script setup>
import { itemAddService, itemChangeStateService, itemDeleteService, itemEditService, itemListWithConditionService, itemProductListService } from '@/api/catalog'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
//导入token
import { userTokenStore } from '@/store/token'
const tokenStore = userTokenStore();
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox, messageConfig } from 'element-plus'

//状态数据模型
const statusOptions = ref([
    { label: '上架', value: 'P' },
    { label: '售罄', value: 'SO' }
]);

//商品所属产品数据模型
const products = ref(["AV-CB-01", "AV-SB-02", "FI-FW-01", "FI-SW-01", "FI-SW-02", "FI-SW-03"])
//商品数据模型
const items = ref([
    {
        "itemId": "EST-1",
        "productId": "FI-SW-01",
        "listPrice": 16.20,
        "unitCost": 10,
        "supplierId": 1,
        "status": "P",
        "attribute1": "Large",
        "img": "111",
        "qty":10000
    },
    {
        "itemId": "EST-10",
        "productId": "K9-DL-01",
        "listPrice": 18.50,
        "unitCost": 10,
        "supplierId": 1,
        "status": "P",
        "attribute1": "Spotted Adult Female",
        "img": "111",
        "qty":10000
    },
    {
        "itemId": "EST-11",
        "productId": "RP-SN-01",
        "listPrice": 18.50,
        "unitCost": 10,
        "supplierId": 1,
        "status": "P",
        "attribute1": "Venomless",
        "img": "111",
        "qty":10000
    },
])
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
//用户搜索时选中的产品id
const productIdForSearch = ref('')
//用户搜索时选中的商品状态
const state = ref('')

//使用标题共用编辑框
const title = ref('');
//控制抽屉是否显示
const visibleDrawer = ref(false)
//改变当前商品状态模型
const hashmap = new Map([['P', '上架'], ['SO', '售罄']]);

//添加表单数据模型
const itemModel = ref({
    itemId: '',
    productId: '',
    listPrice: 0,
    unitCost: 0,
    supplierId: '',
    status: '',
    attribute1: '',
    img: '',
    qty:''
})

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size;
    getItemWithCondition();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    getItemWithCondition();
}

//获取Item商品所属产品列表
const getItemProduct = async () => {
    let result = await itemProductListService();
    if (result) {
        products.value = result.data;
        console.log(products);
    }
}
getItemProduct();
//获取Item商品详情
const getItemWithCondition = async () => {
    //处理数据
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        productIdForSearch: productIdForSearch.value ? productIdForSearch.value : null,
        state: state.value ? state.value : null
    }
    let result = await itemListWithConditionService(params);
    console.log(result);
    if (result) {
        total.value = result.data.total;
        items.value = result.data.list;
        console.log(items.value);

    }
}
getItemWithCondition();


//清空数据回显
const clearData = () => {
    itemModel.value.itemId = '';
    itemModel.value.productId = '';
    itemModel.value.listPrice = '';
    itemModel.value.unitCost = '';
    itemModel.value.qty = '';
    itemModel.value.status = '';
    itemModel.value.attribute1 = '';
    itemModel.value.img = '';
}
//展示添加drawer
const showAddDrawer = () => {
    clearData();
    title.value = '添加商品';
    visibleDrawer.value = true;
}
//上传回显函数
const uploadSuccess = (result) => {
    itemModel.value.img = result.data;
    ElMessage('添加图片成功');
}
//展示编辑drawer
const showEditDrawer = (row) => {
    title.value = '编辑商品';
    visibleDrawer.value = true;
    //显示数据
    itemModel.value.itemId = row.itemId;
    itemModel.value.productId = row.productId;
    itemModel.value.listPrice = row.listPrice;
    itemModel.value.unitCost = row.unitCost;
    itemModel.value.qty = row.qty;
    itemModel.value.status = row.status;
    itemModel.value.attribute1 = row.attribute1;
    itemModel.value.img = row.img;
}
//添加item
const add = async () => {
    itemModel.value.supplierId = 1;
    let result = await itemAddService(itemModel.value);
    ElMessage(result.message ? result.message : '添加成功');
    visibleDrawer.value = false;
    //保持条件查找
    getItemWithCondition();
}
//编辑item
const edit = async () => {
    itemModel.value.supplierId = 1;
    let result = await itemEditService(itemModel.value);
    ElMessage(result.message ? result.message : '编辑成功');
    visibleDrawer.value = false;
    //保持条件查找
    getItemWithCondition();
}
//发布商品，可以是添加商品或者编辑商品
const publishItem = () => {
    title.value === '添加商品' ? add() : edit();
}

//删除商品
const deletefor = async (itemid) => {
    let result = await itemDeleteService(itemid);
    ElMessage(result.message ? result.message : '删除成功');
    getItemWithCondition();
}
//删除商品弹窗
const deleteBox = (itemid) => {
    ElMessageBox.confirm(
        '您确定要删除这个商品吗',
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deletefor(itemid);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
}
//有条件搜索
const search = () => {
    getItemWithCondition();
    ElMessage('获取成功');
}
//无条件搜索,用于重置
const searchWithNoCondition = () => {
    productIdForSearch.value = null;
    state.value = null;
    getItemWithCondition();
    ElMessage('获取成功');
}

//删除产品
const changeStatus = async (itemId, state) => {
    if (state === 'P') {
        state = 'SO';
    } else {
        state = 'P';
    }
    let result = await itemChangeStateService(itemId, state);
    ElMessage(result.message ? result.message : '操作成功');
    getItemWithCondition();
}
//改变状态
const changeStatusBox = (itemId, state) => {
    ElMessageBox.confirm(
        '您确定改变商品' + itemId + '的 ' + hashmap.get(state) + ' 状态吗',
        '注意',
        {
            confirmButtonText: '改变',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            changeStatus(itemId, state);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '改变取消',
            })
        })
}

//表单验证
const rules = {
    itemId: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]{2,10}$/, message: '请输入2-10位字母数字的组合', trigger: 'blur' }
    ],
    listPrice: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^\d{1,10}$/, message: '请输入10位以内的数字', trigger: 'blur' }
    ],
    unitCost: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^\d{1,10}$/, message: '请输入10位以内的数字', trigger: 'blur' }
    ],
    attribute1: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^.{1,30}$/, message: '请输入不超过30位的内容', trigger: 'blur' }    
    ],
    img: [
        { required: true, message: "不能为空", trigger: 'blur' }
    ],
    productId: [
        { required: true, message: "不能为空", trigger: 'blur' }
    ],
    qty: [
        { required: true, message: "不能为空", trigger: 'blur' }
    ],
    status: [
        { required: true, message: "不能为空", trigger: 'blur' }
    ]
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>Item商品管理</span>
                <div class="extra">
                    <el-button type="primary" @click="showAddDrawer()">添加商品</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="所属产品：">
                <el-select placeholder="请选择" v-model="productIdForSearch" style="width: 100px;">
                    <el-option v-for="c in products" :key="c" :label="c" :value="c">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 100px;">
                    <el-option v-for="c in statusOptions" :key="c.value" :label="c.label" :value="c.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search()">搜索</el-button>
                <el-button @click="searchWithNoCondition()">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- Item列表 -->
        <el-table :data="items" style="width: 100%">
            <el-table-column label="图片" prop="status" width="110">
                <template #default="{ row }">
                    <el-image style="width: 100px; height: 100px" :src="row.img" fit="cover"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="商品Id" prop="itemId"></el-table-column>
            <el-table-column label="所属产品Id" prop="productId"></el-table-column>
            <el-table-column label="单价" prop="listPrice"> </el-table-column>
            <el-table-column label="成本价" prop="unitCost"></el-table-column>
            <el-table-column label="供应商" prop="supplierId"></el-table-column>
            <el-table-column label="库存" prop="qty"></el-table-column>
            <!-- <el-table-column label="状态" prop="status"></el-table-column> -->
            <el-table-column label="状态" prop="status">
                <template #default="{ row }">
                    <!-- 使用 hashmap 获取对应的文本 -->
                    {{ hashmap.get(row.status) || '未知状态' }}
                </template>
            </el-table-column>
            <!-- 使用这个#default{row} -->
            <el-table-column label="描述" prop="attribute1"></el-table-column>
            <el-table-column label="操作" width="110">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showEditDrawer(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteBox(row.itemId)"></el-button>
                </template>
            </el-table-column>
            <el-table-column label="改变状态">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit"
                        @click="changeStatusBox(row.itemId, row.status)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加/编辑商品表单 -->
            <el-form :model="itemModel" :rules="rules" label-width="100px">
                <el-form-item label="商品id" prop="itemId">
                    <el-input v-model="itemModel.itemId" placeholder="请输入" :disabled="title === '编辑商品'"></el-input>
                </el-form-item>
                <el-form-item label="所属产品id" prop="productId">
                    <el-select placeholder="请选择" v-model="itemModel.productId">
                        <el-option v-for="c in products" :key="c" :label="c" :value="c">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select placeholder="请选择" v-model="itemModel.status">
                        <el-option v-for="c in statusOptions" :key="c.value" :label="c.label" :value="c.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单价" prop="listPrice">
                    <el-input v-model="itemModel.listPrice" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="成本价" prop="unitCost" >
                    <el-input v-model="itemModel.unitCost" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="qty">
                    <el-input v-model="itemModel.qty" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="attribute1">
                    <el-input v-model="itemModel.attribute1" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="img">
                    <!-- 
                        auto-upload自动上传
                        action:接口路径
                        name:设置的文件字段名
                        header：token
                        on-success成功回调函数
                    -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
                        <img v-if="itemModel.img" :src="itemModel.img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <!-- 图片回调函数todo -->
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" width="500px" @click="publishItem()">完成</el-button>
                </el-form-item>
                <!-- 完成按钮增大宽度todo -->
            </el-form>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>